package com.lhh.sysadmin.config;

import com.lhh.sysadmin.common.security.LoginFailureHandler;
import com.lhh.sysadmin.common.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * spring security配置
 * @author lhh
 * @Date 2024-09-18-52 16:52
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    private static final String URL_WHITELIST[] = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
            "/test/**"
    };

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        super.configure(auth);
    }
    protected void configure(HttpSecurity http) throws Exception{
        // 开启跨域 以及csrf攻击 关闭
        http
                .cors()
                .and()
                .csrf()
                .disable()
                // 登录登出配置
                .formLogin()
            .successHandler(loginSuccessHandler)
            .failureHandler(loginFailureHandler)
//        .and()
//            .logout()
//            .logoutSuccessHandler()
        // session禁用配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态
                // 拦截规则配置
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll() // 白名单 放行
                .anyRequest().authenticated();
        // 异常处理
        // 自定义过滤器配置
    }
}
